package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements IWeChatService {

    private final static String OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final static String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private final static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";

    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String secret;


    @Override
    public String getOpenid(String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type","authorization_code");
        String result = HttpUtil.get(OPEN_ID_URL, map);
        JSONObject json = new JSONObject(result);

        if (json.getInt("errcode") == null || json.getInt("errcode") == 0) {
            String openid = json.getStr("openid");
            return openid;
        }else{
            throw new RuntimeException("获取openid失败" + json.toJSONString(2));
        }
    }


    /**
     * 获取手机号
     * @param detailCode
     * @return
     */
    @Override
    public String getPhone(String detailCode) {

        String token = getToken();
        String url = PHONE_REQUEST_URL + token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", detailCode);
        // 发起请求
        String result = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        // 是一个map
        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 判断接口响应是否出错
        if(jsonObject.getInt("errcode") != 0) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
    private String getToken() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appid);
        map.put("secret", secret);
        String result = HttpUtil.get(TOKEN_URL,map);
        JSONObject json = JSONUtil.parseObj(result);
        if (json.getInt("errcode") == null || json.getInt("errcode") == 0) {
            String access_token = json.getStr("access_token");
            return access_token;

        } else {
            throw new RuntimeException("获取access_token失败" + json.toJSONString(2));
        }

    }
}
